package cn.aylog.service.impl;

import cn.aylog.dao.UserMapper;
import cn.aylog.pojo.User;
import cn.aylog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public User getById(Integer id) {
        return userMapper.selectById(id);
    }

    @CacheEvict(value = "realTimeCache", allEntries = true)
    @Override
    public void updateInfo() {
        User user1 = getById(55);
        User user2 = getById(56);
        System.out.println(user1);
        System.out.println(user2);
        user1.setAge(user1.getAge() + 1);
        user2.setAge(user2.getAge() + 1);
        userMapper.update(user1);
        user1 = getById(55);
//        int i = 1 / 0;
        userMapper.update(user2);
        user2 = getById(56);
    }


//    @Override
//    public Integer getCount() {
//        final String COUNT = "userCount";
//        ValueOperations<Object, Object> ops = redisTemplate.opsForValue();
//        // 先从redis中获取数据
//        Object count = ops.get(COUNT);
//        // 不存在指定的数据， 从数据库中获取并存到数据库
//        if(count == null) {
//            System.out.println("从数据库中获取数据");
//            count = userMapper.getCount();
//            ops.set(COUNT, count, 10, TimeUnit.SECONDS);
//        } else {
//            System.out.println("从redis中获取数据");
//        }
//        return (Integer) count;
//    }

    @Override
    public Integer getCount() {
        final String COUNT = "userCount";
        BoundValueOperations<Object, Object> ops = redisTemplate.boundValueOps(COUNT);
        // 先从redis中获取数据
        Object count = ops.get();
        // 不存在指定的数据， 从数据库中获取并存到数据库
        if(count == null) {
            synchronized (this) {
                count = ops.get();
                if(count == null) {
                    System.out.println("从数据库中获取数据");
                    count = userMapper.getCount();
                    ops.set(count, 10, TimeUnit.SECONDS);
                }
            }
        } else {
            System.out.println("从redis中获取数据");
        }
        return (Integer) count;
    }

}
